package com.ruoyi.flow.auth.security.sso;

import com.ruoyi.flow.common.utils.HttpUtils;
import com.ruoyi.flow.auth.security.sso.SsoUsernamePassword;
import com.ruoyi.flow.auth.security.sso.SsoUsernamePasswordProvider;
import com.ruoyi.flow.flow.identity.activiti.entity.FlowUser;
import com.ruoyi.flow.flow.identity.activiti.repository.FlowUserRepository;
import org.apache.commons.lang3.StringUtils;
import org.springframework.http.HttpStatus;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import java.io.IOException;
import java.util.Map;
import java.util.Objects;

import static com.google.common.base.Preconditions.checkState;

/**
 * 基于Nebula或者网安云发起的单点登录获取用户名密码
 *
 * @author wtian
 * @version 1.0
 * @since 2018/9/12 15:04
 */
public class NebulaSsoUsernamePasswordProvider implements SsoUsernamePasswordProvider {
    @Resource
    private FlowUserRepository repository;
    /**
     * 向网安云请求获取警员号的url地址
     */
    private String url;
    /**
     * 从网安云发送请求过来后面携带的ticket名称
     */
    private String ticketName;

    @Override
    public SsoUsernamePassword getUsernameAndPassword(Map<String, String[]> parameters) {
        String token = Objects.toString(parameters.get(ticketName), "");
        checkState(StringUtils.isNotEmpty(token), "The token named {} from nebula is null.", ticketName);
        //根据token调用nebula接口获取警员号
        String url = this.url + token;
        HttpUtils utils = HttpUtils.defaults(url);
        String policeNo = null;
        try {
            boolean geted = utils.doGet();
            if (geted && utils.getResponseCode() == HttpStatus.OK.value()) {
                policeNo = utils.getResponseAsString();
            }
        } catch (IOException e) {
            e.printStackTrace();
        }
        checkState(StringUtils.isNotEmpty(policeNo), "Can not get policeno from nebula with token [{}]", token);
        FlowUser flowUser = repository.findByPoliceNo(policeNo);
        checkState(Objects.nonNull(flowUser), "Can not get User with policeno [{}]", policeNo);
        SsoUsernamePassword usernamePassword = new SsoUsernamePassword();
        usernamePassword.setUsername(flowUser.getId());
        usernamePassword.setPassword(flowUser.getPassword());
        return usernamePassword;
    }

    @Override
    public boolean matchRequest(HttpServletRequest request) {
        return StringUtils.isNotEmpty(request.getParameter(ticketName));
    }

    public String getUrl() {
        return url;
    }

    public void setUrl(String url) {
        this.url = url;
    }

    public String getTicketName() {
        return ticketName;
    }

    public void setTicketName(String ticketName) {
        this.ticketName = ticketName;
    }
}
